<template>
<div class="user-profile-container">
  <!-- 个人信息编辑卡片 -->
  <el-card class="profile-card">
    <template #header>
      <span>个人信息</span>
    </template>
    <el-form
      ref="profileFormRef"
      :model="userInfo"
      :rules="profileRules"
      label-width="120px"
      label-position="left"
    >
      <!-- 头像上传 -->
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>

      <!-- 手机号码 -->
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="userInfo.phone" placeholder="请输入手机号码" />
      </el-form-item>

      <!-- 邮箱 -->
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userInfo.email" placeholder="请输入邮箱" />
      </el-form-item>

      <!-- 修改密码 -->
      <el-form-item label="修改密码" prop="password">
        <el-button type="text" @click="openPasswordDialog">修改密码</el-button>
      </el-form-item>

      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitProfileForm">保存修改</el-button>
        <el-button @click="resetProfileForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 修改密码弹窗 -->
  <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px">
    <el-form
      ref="passwordFormRef"
      :model="passwordForm"
      :rules="passwordRules"
      label-width="100px"
    >
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="passwordForm.phone" placeholder="请输入手机号码" />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="passwordForm.code" placeholder="请输入验证码" />
        <el-button type="text" @click="sendSmsCode">发送验证码</el-button>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="passwordForm.newPassword"
          type="password"
          placeholder="请输入新密码"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="passwordDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitPasswordForm">确定</el-button>
    </template>
  </el-dialog>
</div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import axios from 'axios';

// 用户信息
interface UserInfo {
  avatar: string;
  phone: string;
  email: string;
}

// 修改密码表单
interface PasswordForm {
  phone: string;
  code: string;
  newPassword: string;
}

const userInfo = reactive<UserInfo>({
  avatar: '',
  phone: '',
  email: ''
});

const profileFormRef = ref<FormInstance>();
const profileRules = reactive<FormRules<UserInfo>>({
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
});

const passwordDialogVisible = ref(false);
const passwordForm = reactive<PasswordForm>({
  phone: '',
  code: '',
  newPassword: ''
});
const passwordFormRef = ref<FormInstance>();
const passwordRules = reactive<FormRules<PasswordForm>>({
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
});

// 打开修改密码弹窗
const openPasswordDialog = () => {
  passwordDialogVisible.value = true;
};

// 发送验证码
const sendSmsCode = async () => {
  if (!passwordForm.phone) {
    ElMessage.error('请输入手机号码');
    return;
  }
  try {
    const response = await axios.post('/user/sendSms', passwordForm.phone);
    if (response.data.success) {
      ElMessage.success('验证码发送成功');
    } else {
      ElMessage.error(response.data.message || '验证码发送失败');
    }
  } catch (error) {
    ElMessage.error('验证码发送失败');
  }
};

// 提交修改密码表单
const submitPasswordForm = async () => {
  if (!passwordFormRef.value) return;
  try {
    await passwordFormRef.value.validate();
    const response = await axios.put('/user/updatePassword', passwordForm);
    if (response.data.success) {
      ElMessage.success('密码修改成功');
      passwordDialogVisible.value = false;
    } else {
      ElMessage.error(response.data.message || '密码修改失败');
    }
  } catch (error) {
    ElMessage.error('表单验证失败');
  }
};

// 头像上传处理
const handleAvatarSuccess = (response:any) => {
  userInfo.avatar = response.data.url; // 假设后端返回的头像 URL 存储在 response.data.url 中
};

const beforeAvatarUpload = (rawFile:any) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!');
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 提交个人信息表单
const submitProfileForm = async () => {
  if (!profileFormRef.value) return;
  try {
    await profileFormRef.value.validate();
    const updatedUserInfo = {
      avatarUrl: userInfo.avatar,
      phone: userInfo.phone,
      email: userInfo.email
    };

    const response = await axios.put('/user/updateUser', updatedUserInfo);
    if (response.data.success) {
      ElMessage.success('个人信息修改成功');
    } else {
      ElMessage.error(response.data.message || '修改失败');
    }
  } catch (error) {
    ElMessage.error('表单验证失败');
  }
};

// 重置个人信息表单
const resetProfileForm = () => {
  if (!profileFormRef.value) return;
  profileFormRef.value.resetFields();
};
</script>
<style scoped>
.user-profile-container {
  max-width: 1000px;
  margin: 40px auto;
  padding: 20px;
}

.profile-card,
.address-card {
  margin-bottom: 20px;
}

.avatar-uploader
:deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>
